const iconv = require('iconv-lite');
const moment = require('moment');
const axios = require('axios');
const fs = require('fs'); // 引入fs模块
const https = require('https'); // 引入fs模块
const path = require('path'); // 引入fs模块
const URL = require('url'); // 引入fs模块


const SocksProxyAgent = require('socks-proxy-agent');
const proxy = 'socks5://127.0.0.1:1086';
const agent = new SocksProxyAgent(proxy);
https.globalAgent = agent

const feedsCache = {}

module.exports = {
    summary: '',

    async beforeSendResponse(requestDetail, responseDetail) {
        let intercept = false
        let body
        if (requestDetail.url.indexOf('/aweme/v1/feed') > -1) {
            intercept = true
            body = iconv.decode(responseDetail.response.body, 'utf8')

            // responseDetail.response.body = body
            // console.log(body)

            process(body)

        } else if (requestDetail.url.indexOf('/aweme/v1/play') > -1) {
            intercept = true
            body = iconv.decode(responseDetail.response.body, 'utf8')
            const m = body.match(/"(.*)"/)
            if (m) {
                const video_id = requestDetail.url.match(/video_id=(.*?)&/)[1]
                const video_url = m[1].replace(/&amp;/g, '&')
                if (feedsCache[video_id]) {
                    const feed = feedsCache[video_id]
                    feed.video_url = video_url
                    console.log(feed)
                    try {
                        await download(feed)
                    } catch (e) {
                        console.log('err', e)
                    }
                } else {
                    console.log('没找到', video_id)
                }
            }

        }

        if (intercept) {
            // console.log('xxx', requestDetail.url)
        }

        return null;
    },
};

//处理
function process(body) {
    const res = JSON.parse(body)

    res.aweme_list.map((feed, i) => {
        const url = feed.video.download_addr.url_list[0]
        const video_id = url.match(/video_id=(.*?)&/)[1]
        const {desc} = feed
        const {nickname, uid, signature, gender} = feed.author
        const {comment_count, digg_count, download_count, play_count, share_count} = feed.statistics


        feedsCache[video_id] = {
            desc,
            nickname, uid, signature, gender,
            comment_count, digg_count, download_count, play_count, share_count
        }

        //此处更改
        // const filename = moment().format('YYYY-MM-DD_HH/mm/ss') + '_' + i
        //
        // // console.log('ss')
        // // console.log('xxx', )
        // const opt = URL.parse(url)
        // opt.agent = agent
        // https.get(url, res => {
        //     console.log('hhh', res.headers)
        // })


        // download(filename, video_url)
    })
}


//下载
function download(feed) {
    const {video_url, nickname, digg_count, comment_count} = feed

    const filename = `${nickname}_${digg_count}_${comment_count}`

    return new Promise((resolve => {
        axios.get(video_url, {
            responseType: 'arraybuffer',
        }).then(res => {
            fs.writeFile(path.join(getDir(), filename + '.mp4'), res.data, function (r) {
                console.log(filename, 'ok')
                resolve()
            })
        })
    }))
}


//获取保存路径
function getDir() {
    const dirname = moment().format('YYYY-MM-DD')
    const todayDir = path.join(__dirname, '../', 'videos', dirname)

    try {
        //今日的目录是否创建
        fs.statSync(todayDir)
    } catch (e) {
        //今天目录没创建，创建目录
        fs.mkdirSync(todayDir)
    }

    return todayDir
}
